<template>
  <div class="work-order-task-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Memo /></el-icon>
          <span>工单任务</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form
        :model="searchForm"
        class="filter-form"
        inline
        @keyup.enter="handleSearch"
      >
        <el-form-item>
          <el-input
            v-model="searchForm.taskCodeOrName"
            placeholder="请输入任务编号/名称"
            clearable
            class="w-220"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.workOrderNameOrCode"
            placeholder="请输入工单名称/编号"
            clearable
            class="w-220"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.processId"
            placeholder="请选择工序"
            clearable
            filterable
            class="w-180"
          >
            <el-option
              v-for="item in processOptions"
              :key="item.id"
              :label="item.processName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-180">
            <el-option label="未派工" :value="0" />
            <el-option label="已派工" :value="1" />
            <el-option label="已下达" :value="2" />
            <el-option label="进行中" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已关闭" :value="5" />
            <el-option label="已暂停" :value="6" />
            <el-option label="已撤回" :value="7" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="success" @click="handleDispatch">派工</el-button>
        <el-button type="primary" plain @click="handleReportWork">报工</el-button>
        <el-button type="danger" plain @click="handleClose">关闭</el-button>
      </div>

      <el-table
        :data="rows"
        border
        stripe
        :loading="loading"
        height="640"
        class="task-table"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="taskCode" label="任务编号" min-width="150" />
        <el-table-column prop="taskName" label="任务名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="siteName" label="站点名称" min-width="140" />
        <el-table-column prop="workOrderCode" label="工单编号" min-width="150" />
        <el-table-column prop="workOrderName" label="工单名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="processRouteName" label="工艺流程" min-width="140" />
        <el-table-column prop="processName" label="工序名称" min-width="140" />
        <el-table-column prop="processCode" label="工序编号" min-width="140" />
        <el-table-column label="任务颜色" width="120" align="center">
          <template #default="scope">
            <el-color-picker v-model="scope.row.taskColor" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="planQuantity" label="计划数量" width="120" align="center" />
        <el-table-column prop="actualQuantity" label="实际生产" width="120" align="center" />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ statusName(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="primary"
              link
              @click="handleDispatchRow(scope.row)"
            >
              派工
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              type="success"
              link
              @click="handleStartWork(scope.row)"
            >
              开工
            </el-button>
            <el-button
              v-if="scope.row.status === 2 || scope.row.status === 5"
              type="danger"
              link
              @click="handleCloseRow(scope.row)"
            >
              关闭
            </el-button>
            <el-button
              v-if="scope.row.status === 3"
              type="primary"
              link
              @click="handleReportWorkRow(scope.row)"
            >
              报工
            </el-button>
            <el-button
              v-if="scope.row.status === 3"
              type="success"
              link
              @click="handleComplete(scope.row)"
            >
              完成
            </el-button>
            <el-button
              v-if="scope.row.status === 4 || scope.row.status === 5"
              type="warning"
              link
              @click="handleRestart(scope.row)"
            >
              重启
            </el-button>
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

  </div>
</template>

<script setup lang="ts">
import { ArrowRight, HomeFilled, Memo, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface WorkOrderTaskItem {
  id: number
  taskCode: string
  taskName: string
  workOrderId: number
  workOrderCode: string
  workOrderName: string
  siteName: string
  siteCode?: string
  processRouteCode?: string
  processRouteName?: string
  processId: number
  processName: string
  processCode?: string
  taskColor?: string
  planQuantity: number
  actualQuantity: number
  qualifiedQuantity: number
  status: number
}

interface ProcessOption {
  id: number
  processName: string
}

const router = useRouter()
const loading = ref(false)
const rows = ref<WorkOrderTaskItem[]>([])
const multipleSelection = ref<WorkOrderTaskItem[]>([])

const pager = reactive({
  page: 1,
  size: 10,
  total: 0,
});

const searchForm = reactive({
  taskCodeOrName: '',
  workOrderNameOrCode: '',
  processId: undefined as number | undefined,
  status: undefined as number | undefined
})

const processOptions = ref<ProcessOption[]>([])

// 生成假数据
const generateMockData = (): WorkOrderTaskItem[] => {
  const mockData: WorkOrderTaskItem[] = []
  const statuses = [0, 1, 2, 3, 4, 5, 6, 7]
  const processes = [
    { id: 1, name: '工序一', code: 'GX001' },
    { id: 2, name: '工序二', code: 'GX002' },
    { id: 3, name: '工序三', code: 'GX003' },
    { id: 4, name: '工序四', code: 'GX004' },
    { id: 5, name: '工序五', code: 'GX005' }
  ]
  const sites = ['站点A', '站点B', '站点C', '站点D', '站点E']
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  
  for (let i = 1; i <= 20; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const process = processes[Math.floor(Math.random() * processes.length)]
    const planQuantity = Math.floor(Math.random() * 1000) + 100
    const actualQuantity = Math.floor(planQuantity * (Math.random() * 0.8))
    const qualifiedQuantity = Math.floor(actualQuantity * 0.95)
    
    mockData.push({
      id: i,
      taskCode: `RW${String(i).padStart(6, '0')}`,
      taskName: `${process.name}任务${i}`,
      workOrderId: Math.floor(i / 3) + 1,
      workOrderCode: `GD${String(Math.floor(i / 3) + 1).padStart(6, '0')}`,
      workOrderName: `工单${Math.floor(i / 3) + 1}`,
      siteName: sites[Math.floor(Math.random() * sites.length)],
      siteCode: `SITE${String(i % 5 + 1).padStart(3, '0')}`,
      processRouteCode: `PR${String(i % 3 + 1).padStart(3, '0')}`,
      processRouteName: `工艺路线${i % 3 + 1}`,
      processId: process.id,
      processName: process.name,
      processCode: process.code,
      taskColor: colors[Math.floor(Math.random() * colors.length)],
      planQuantity,
      actualQuantity,
      qualifiedQuantity,
      status
    })
  }
  return mockData
}

const fetchList = async () => {
  loading.value = true
  try {
    // 暂时使用假数据
    await new Promise(resolve => setTimeout(resolve, 500)) // 模拟网络延迟
    const mockData = generateMockData()
    
    // 应用筛选条件
    let filteredData = mockData
    if (searchForm.taskCodeOrName) {
      const keyword = searchForm.taskCodeOrName.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.taskCode.toLowerCase().includes(keyword) || 
        item.taskName.toLowerCase().includes(keyword)
      )
    }
    if (searchForm.workOrderNameOrCode) {
      const keyword = searchForm.workOrderNameOrCode.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.workOrderCode.toLowerCase().includes(keyword) || 
        item.workOrderName.toLowerCase().includes(keyword)
      )
    }
    if (searchForm.processId !== undefined) {
      filteredData = filteredData.filter(item => item.processId === searchForm.processId)
    }
    if (searchForm.status !== undefined) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    // 分页
    const start = (pager.page - 1) * pager.size
    const end = start + pager.size
    rows.value = filteredData.slice(start, end)
    pager.total = filteredData.length

    // 提取工序选项
    const processSet = new Map<number, ProcessOption>()
    mockData.forEach(item => {
      if (!processSet.has(item.processId)) {
        processSet.set(item.processId, { id: item.processId, processName: item.processName })
      }
    })
    processOptions.value = Array.from(processSet.values())
    
    // 真实API调用（暂时注释）
    // const response = await https.Reads.get('/AShow/WorkOrderTaskList', {
    //   params: {
    //     taskCodeOrName: searchForm.taskCodeOrName || undefined,
    //     workOrderNameOrCode: searchForm.workOrderNameOrCode || undefined,
    //     processId: searchForm.processId,
    //     status: searchForm.status,
    //     pageindex: pager.page,
    //     pagesize: pager.size
    //   }
    // })
    // const payload = extractPayload(response)
    // if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
    //   throw new Error(getResponseMessage(payload, '获取任务列表失败'))
    // }
    // rows.value = payload?.data ?? payload?.Data ?? []
    // pager.total = payload?.totalCount ?? payload?.TotalCount ?? rows.value.length

    // // 提取工序选项
    // const processSet = new Map<number, ProcessOption>()
    // rows.value.forEach(item => {
    //   if (!processSet.has(item.processId)) {
    //     processSet.set(item.processId, { id: item.processId, processName: item.processName })
    //   }
    // })
    // processOptions.value = Array.from(processSet.values())
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取任务列表失败'))
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pager.page = 1
  fetchList()
}

const handleReset = () => {
  searchForm.taskCodeOrName = ''
  searchForm.workOrderNameOrCode = ''
  searchForm.processId = undefined
  searchForm.status = undefined
  pager.page = 1
  fetchList()
}

const onSelectionChange = (val: WorkOrderTaskItem[]) => {
  multipleSelection.value = val;
};

const onPageSizeChange = (size: number) => {
  pager.size = size
  pager.page = 1
  fetchList()
}

const onPageChange = (page: number) => {
  pager.page = page
  fetchList()
}

const handleDispatch = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择需要派工的任务')
    return
  }
  if (multipleSelection.value.length > 1) {
    ElMessage.warning('请一次只选择一个任务进行派工')
    return
  }
  handleDispatchRow(multipleSelection.value[0]!)
}

const handleDispatchRow = (row: WorkOrderTaskItem) => {
  router.push({ path: '/WorkOrderDispatch', query: { id: row.id } })
}

const handleReportWork = () => {
  ElMessage.info('报工功能开发中')
}

const handleReportWorkRow = (row: WorkOrderTaskItem) => {
  ElMessage.info(`报工任务：${row.taskCode}`)
}

const handleClose = () => {
  ElMessage.info('关闭功能开发中')
}

const handleCloseRow = (row: WorkOrderTaskItem) => {
  ElMessage.info(`关闭任务：${row.taskCode}`)
}

const handleStartWork = (row: WorkOrderTaskItem) => {
  ElMessage.info(`开工任务：${row.taskCode}`)
}

const handleComplete = (row: WorkOrderTaskItem) => {
  ElMessage.info(`完成任务：${row.taskCode}`)
}

const handleRestart = (row: WorkOrderTaskItem) => {
  ElMessage.info(`重启任务：${row.taskCode}`)
}

const handleView = (row: WorkOrderTaskItem) => {
  router.push({ path: '/TaskDetail', query: { id: row.id } })
}

const statusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'success'
    case 4:
      return 'success'
    case 5:
      return 'danger'
    case 6:
      return 'warning'
    case 7:
      return 'info'
    default:
      return 'info'
  }
};

const statusName = (status: number) => {
  const names: Record<number, string> = {
    0: '未派工',
    1: '已派工',
    2: '已下达',
    3: '进行中',
    4: '已完成',
    5: '已关闭',
    6: '已暂停',
    7: '已撤回'
  }
  return names[status] ?? '未知'
}

onMounted(() => {
  fetchList();
});
</script>

<style scoped>
.work-order-task-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.filter-card,
.table-card {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.task-table {
  width: 100%;
}

.mt-12 {
  margin-top: 12px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
}

.w-180 {
  width: 180px;
}

.w-220 {
  width: 220px;
}
</style>
